"""用户注册"""
import json
import binascii
# 加密密码函数
import hashlib
import random
import string
import sm3
import sm2test
import sm4test
import func
def addsalt():
    active = 0
    #激活while时使用
    salts = ''
    #先建一个空白字符串
    while active < 10:
        #用while循环随机生成一个6位数验证码
        salt_one = random.choice(string.digits)
        salts += salt_one

        active += 1
    return salts
before_salt = addsalt()
print('salt为')
print(before_salt)

#用hash函数加密密码
def secret(password):
    pws = before_salt+password
    after_password = sm3.sm3_hash(func.bytes_to_list(pws))
    
    return after_password

def encsalt(salt):
    plaintext_bytes = sm4test.exp_SM4_str(salt)
    key_bytes = sm4test.get_key()   
    ciphertexts = sm4test.SM4_ecb_enc(plaintext_bytes,key_bytes)
    ciphertexts=func.bytes_to_list(ciphertexts)
    emm = ','.join(map(str, ciphertexts))
    emm = emm.replace(',', ' ')
    ecm = sm2test.sm2e(emm)
    ecm1=func.bytes_to_list(ecm)
    ecm1 = ','.join(map(str, ecm1))
    ecm_f = open("salt.txt", 'wb')
    ecm_f.write(ecm)
    keytexts = func.bytes_to_list(key_bytes)
    ky = ','.join(map(str, keytexts))
    ky = ky.replace(',', ' ')
    kym = sm2test.sm2ee(ky)
    kym_f = open("sm4key.txt", 'wb')
    kym_f.write(kym)
    return ecm1

def register():
    """用户注册"""    
    filename = 'users.txt'
    users = {}
    namecheck = []
    
    import os #检测用户信息是否存在
    file_exist = os.path.exists(filename)
    if not file_exist:
        with open(filename, 'w'):
            print('你是第一个注册的用户！！！')


    with open(filename, 'r+') as file:
        names = file.read().splitlines()
        for name in names:
            name = eval(name)
            namecheck.append(name['username'])
        namecheck = [name.lower() for name in namecheck]
        while True:
            username = input('请输入您要注册的用户名：')
            if username.lower() in namecheck:
                print('用户名已存在,请重试！！！')
                continue
            elif len(username.strip()) == 0:
                print('用户名不为空！！！')
                continue
            users['username'] = username
            
            password = input('请输入密码：')
            users['password'] = password #如果不想显示出用户的真实密码可以把这行代码删除
            users['password_hash'] = secret(password)
            lastsalt=encsalt(before_salt)
            users['salt'] = lastsalt

            # 加密密码

            users = json.dumps(users, ensure_ascii=False)
            users += f'\n'
            file.write(users)
            print(f'注册成功！！！\n')
            break
